<template>
  <div>
    <div class="page-form">
      <el-select
        v-model="queryParams.questionId"
        placeholder="全部题组"
        clearable
        @change="handleSearch"
        filterable
      >
        <el-option
          v-for="item in questionList"
          :key="item.id"
          :label="
            item.questionGroupName
              ? item.questionGroupName
              : item.smallQuestionNumber !== 0
              ? item.smallQuestionNumber
              : item.questionNumber
          "
          :value="item.id"
        />
      </el-select>
      <el-select
        v-hasRole="['admin']"
        v-model="queryParams.schoolId"
        placeholder="全部学校"
        clearable
        @change="handleSearch"
        filterable
      >
        <el-option
          v-for="item in schoolList"
          :key="item.id"
          :label="item.schoolName"
          :value="item.id"
        />
      </el-select>
      <el-select
        v-model="queryParams.complete"
        placeholder="状态"
        clearable
        @change="handleSearch"
      >
        <el-option label="已完成" :value="1" />
        <el-option label="未完成" :value="2" />
      </el-select>
      <el-input
        v-model="queryParams.scnTeacher"
        placeholder="查找教师账号或姓名"
        clearable
        @input="handleSearch"
      />
    </div>
    <el-table
      stripe
      border
      ref="tableList"
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      row-key="userId"
    >
      <el-table-column
        label="题组"
        align="center"
        prop="questionName"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.questionName }}</span
          ><br />
          <span style="font-size: 12px; color: rgba(0, 0, 0, 0.6)">{{
            scope.row.subjects && scope.row.subjects.length
              ? "(" + scope.row.subjects.join("、") + ")"
              : ""
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="学校名称"
        align="center"
        prop="schoolName"
        :show-overflow-tooltip="true"
      />
      <!-- <el-table-column
        label="角色"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          {{ roleFilter(scope.row.role) }}
        </template>
      </el-table-column>
      <el-table-column
        label="手机号&账号"
        align="center"
        prop="phone"
        :show-overflow-tooltip="true"
      /> -->
      <!-- <el-table-column
        label="任务类型"
        align="center"
        prop="reviewSubject"
        :show-overflow-tooltip="true"
      /> -->
      <el-table-column
        label="教师姓名"
        align="center"
        prop="teacherName"
        :show-overflow-tooltip="true"
      /><el-table-column
        label="任务量"
        align="center"
        prop="totalTasks"
        :show-overflow-tooltip="true"
      /><el-table-column
        label="已完成任务量"
        align="center"
        prop="completedTasks"
        :show-overflow-tooltip="true"
      /><el-table-column
        label="剩余任务量"
        align="center"
        prop="remainingTasks"
        :show-overflow-tooltip="true"
      /><el-table-column
        label="评阅进度"
        align="center"
        prop="reviewedRate"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="是否在线"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-link type="primary" v-if="scope.row.online === 'true'"
            >在线</el-link
          >
          <el-link type="danger" v-else>不在线</el-link>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-link type="primary" @click="edit(scope.row)">编辑</el-link>
          <el-link type="danger" @click="del(scope.row.id)">删除</el-link>
        </template>
      </el-table-column> -->
    </el-table>

    <div class="page-bottom">
      <div class="sel-box">
        <!-- <p>
          已选 <span>{{ ids.length }}</span> 项 / 共 {{ total }} 项
        </p> -->
        <el-button type="primary" @click="debouncedSearch">刷新进度</el-button>
        <el-button
          type="primary"
          :loading="exportLoading"
          @click="exportProgress"
          >{{ exportLoading ? "导出中..." : "导出老师进度" }}</el-button
        >
        <el-button type="primary" :loading="exportLoading1" @click="dcxxjd">{{
          exportLoading1 ? "导出中..." : "导出学校进度"
        }}</el-button>
      </div>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script>
import { debounce } from "lodash";
import {
  examTeacherList,
  examTeacherAdd,
  examTeacherEdit,
  examTeacherDel,
  templatemenu,
  templatemenulist,
} from "@/api/xmgl/pyjsgl";
import {
  getPyxqDetailList,
  getPyxqGroupSelect,
  getSchoolSelect,
  exportPyjdProgress,
  exportPyjdProgressschool,
  statistics,
} from "@/api/xmgl/pyjd";
import { schoolsubjectlist, checkPassword } from "@/api/common";
import { teacherlist } from "@/api/jcgl/jsgl";
import { getToken } from "@/utils/auth";
import axios from "axios";
import { schoollist } from "@/api/xmgl/csxx";
import { listRole } from "@/api/system/role";
import { treeselect } from "@/api/system/menu";
import { mount } from "sortablejs";
export default {
  props: {
    xmxx: {},
    xmxklb: null,
    subjectId: null,
    subjectName: undefined,
  },
  data() {
    return {
      loading: false,

      ids: [],

      total: 0,
      tableData: [],

      multiple: true,

      queryParams: {
        questionName: undefined,
        school: undefined,
        complete: undefined,
        scnTeacher: undefined,
        pageNum: 1,
        pageSize: 15,
      },
      questionList: [],
      schoolList: [],
      editKmVisible: false,
      editForm: {
        addType: "1",
        schoolId: "",
        teacherId: "",
        teacherName: "",
        phone: "",
        password: "",
        role: [],
        reviewSubject: [],
      },
      rules: {
        schoolId: [
          { required: true, message: "学校名称不能为空", trigger: "change" },
        ],
        grade: [{ required: true, message: "年级不能为空", trigger: "change" }],
      },

      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 学校
        deptId: "",
        examSchoolId: "",
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/exam/teacher/import",
      },

      xxlb: [],
      jslb: [],
      roleList: [],
      xklb: [],
      teamList: [],

      qxglVisible: false,
      qxData: [],

      exportLoading: false,
      exportLoading1: false,
    };
  },
  watch: {
    subjectId: {
      handler(newVal, oldVal) {
        if (newVal === "0" && oldVal === undefined) {
          return false;
        }
        if (Number(newVal) && oldVal === "0") {
          this.loading = true;
          //   statistics({examId:this.subjectId}).catch(err=>{
          //     this.$message.error('更新数据失败')
          //   }).finally(res=>{
          // console.log(res);
          this.getList();
          // })
        }
        if (Number(newVal) && oldVal === undefined) {
          this.loading = true;
          //   statistics({examId:this.subjectId}).catch(err=>{
          //     this.$message.error('更新数据失败')
          //   }).finally(res=>{
          // console.log(res);
          this.getList();
          // })
        }
        if (Number(newVal) && Number(oldVal)) {
          this.loading = true;
          //   statistics({examId:this.subjectId}).catch(err=>{
          //     this.$message.error('更新数据失败')
          //   }).finally(res=>{
          // console.log(res);
          this.getList();
          // })
        }
        // if(newVal&&oldVal!=0){
        // }
      },
      deep: true,
      // immediate: true, //
    },
  },
  created() {
    this.loading = true;
    statistics({ examId: this.subjectId })
      .catch((err) => {
        this.$message.error("更新数据失败");
      })
      .finally((res) => {});
    this.getSelectList();
  },
  mounted() {},
  methods: {
    getList() {
      this.loading = true;
      this.tableData = [];
      getPyxqDetailList({ ...this.queryParams }, this.subjectId)
        .then((res) => {
          if (res.code === 200) {
            this.tableData = res.data.teachers || [];
            this.total = res.data.total || 0;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取 题组-学校：下拉框列表
    getSelectList() {
      getPyxqGroupSelect({ examId: this.subjectId }).then((res) => {
        if (res.code === 200) {
          this.questionList = res.data.sort((a, b) => {
            return (
              a.questionGroupName - b.questionGroupName ||
              a.smallQuestionNumber - b.smallQuestionNumber ||
              a.questionNumber - b.questionNumber
            );
          });
        }
      });
      getSchoolSelect({ examId: this.subjectId }).then((res) => {
        if (res.code === 200) {
          this.schoolList = res.data;
          if (!this.$auth.hasRole("admin")) {
            this.queryParams.schoolId = this.schoolList.filter((item) => {
              return this.$store.state.user.deptId == item.schoolId;
            })[0].id;
          }
          this.getList();
        }
      });
    },
    debouncedSearch: debounce(function () {
      this.queryParams.pageNum = 1;
      this.loading = true;
      statistics({ examId: this.xmxx.id })
        .catch((err) => {
          this.$message.error("更新数据失败");
        })
        .finally((res) => {
          //   console.log(res);
          this.getList();
          this.$emit('getRefreshTime')
        });
    }, 800),
    // 搜索条件
    handleSearch() {
      this.debouncedSearch();
    },
    // 导出进度
    async exportProgress() {
      this.exportLoading = true;
      // 去除 queryParams 中的分页参数，避免在导出时传递分页信息
      const { pageNum, pageSize, ...paramsWithoutPagination } =
        this.queryParams;
      await exportPyjdProgress({
        ...paramsWithoutPagination,
        examIdMainId: this.xmxx.id,
      })
        .then((res) => {
          // 创建临时链接
          const blob = new Blob([res.data]);
          if (blob.size == 0) {
            this.$modal.alert("当前无进度，无法导出");
            return;
          }
          // this.$download.saveAs(blob, `${this.subjectName}_评阅进度_${new Date().getTime()}.xlsx`);
          // 创建临时链接
          const link = document.createElement("a");
          link.href = window.URL.createObjectURL(blob);
          link.download = `${
            this.xmxx.examName
          }_教师评阅进度_${new Date().getTime()}.xlsx`;
          link.style.display = "none";
          console.log(
            window.URL.createObjectURL(blob),
            "window.URL.createObjectURL(blob)"
          );

          // 触发下载
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(link.href);
          this.$message.success("导出成功");
        })
        .finally(() => {
          this.exportLoading = false;
        });
      // return new Promise((resolve, reject) => {
      //   axios({
      //   method: 'get',
      //   url: '/task/teacher/stats/review/export',
      //   responseType: 'blob',
      //   headers: { 'Authorization': 'Bearer ' + getToken() }
      // }).then((res) => {
      //   const isBlob = blobValidate(res.data);
      //   if (isBlob) {
      //     const blob = new Blob([res.data])
      //     saveAs(blob,`${this.subjectName}_评阅进度_${new Date().getTime()}.xlsx`)
      //   } else {
      //     this.printErrMsg(res.data);
      //   }
      // })
      // });
      return;
      try {
        const res = await exportPyjdProgress(
          { ...this.queryParams, examSubjectId: this.subjectId },
          {
            responseType: "blob", // 必须指定响应类型
          }
        );
        // 创建临时链接
        const blob = new Blob([res.data]);
        const downloadUrl = window.URL.createObjectURL(blob);
        console.log(downloadUrl, "downloadUrl");

        // 从headers获取文件名
        // const fileName = decodeURIComponent(
        //   res.headers['content-disposition']
        //     .split('filename=')[1]
        //     .replace(/"/g, '')
        // ) || `${this.xmxx.name}_评阅进度_${new Date().getTime()}.xlsx`
        console.log(this.subjectName);

        const fileName = `${
          this.subjectName
        }_评阅进度_${new Date().getTime()}.xlsx`;
        // 创建隐藏的a标签触发下载
        const link = document.createElement("a");
        link.href = downloadUrl;
        link.download = fileName;
        link.style.display = "none";
        document.body.appendChild(link);
        link.click();
        // 清理资源
        window.URL.revokeObjectURL(downloadUrl);
        document.body.removeChild(link);
        this.$message.success("文件下载成功");
      } catch (error) {
        console.log(error, "error");
        this.$message.error("文件下载失败");
        return false;
      }
    },

    dcxxjd() {
      this.exportLoading1 = true;
      // 去除 queryParams 中的分页参数，避免在导出时传递分页信息
      exportPyjdProgressschool({
        examIdMainId: this.xmxx.id,
      })
        .then((res) => {
          // 创建临时链接

          const blob = new Blob([res.data]);
          if (blob.size == 0) {
            this.$modal.alert("当前无进度，无法导出");
            return;
          }
          // this.$download.saveAs(blob, `${this.subjectName}_评阅进度_${new Date().getTime()}.xlsx`);
          // 创建临时链接
          const link = document.createElement("a");
          link.href = window.URL.createObjectURL(blob);
          link.download = `${
            this.xmxx.examName
          }_考试进度表_${new Date().getTime()}.xlsx`;
          link.style.display = "none";
          console.log(
            window.URL.createObjectURL(blob),
            "window.URL.createObjectURL(blob)"
          );

          // 触发下载
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(link.href);
          this.$message.success("导出成功");
        })
        .finally(() => {
          this.exportLoading1 = false;
        });
    },
    async printErrMsg(data) {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg =
        errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
      Message.error(errMsg);
    },
    blobValidate(data) {
      return data.type !== "application/json";
    },

    beforeClose(done) {
      this.editForm = {
        addType: "1",
        schoolId: "",
        teacherId: "",
        teacherName: "",
        phone: "",
        password: "",
        role: [],
        reviewSubject: [],
      };
      this.bjlb = [];
      this.xslb = [];
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate();
        done();
      });
    },
    handleClose() {
      this.beforeClose(() => {
        this.editKmVisible = false;
      });
    },

    editSubmit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          let req;
          if (this.editForm.id) {
            req = examTeacherEdit;
          } else {
            req = examTeacherAdd;
          }
          let data = {
            ...this.editForm,
            examId: this.xmxx.id,
          };

          data.schoolId = this.xxlb.filter((item) => {
            return item.schoolId == data.schoolId;
          })[0].id;
          data.role = data.role.join(",");
          data.reviewSubject = data.reviewSubject.join(",");

          if (data.addType == "1") {
            data.teacherName = this.jslb.filter((item) => {
              return item.userId == data.teacherId;
            })[0].nickName;
          }

          req(data)
            .then((res) => {
              this.$modal.msgSuccess("操作成功");
              this.handleClose();
              this.getList();
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    del(id) {
      this.$prompt(
        "删除考生后，可能造成考生数据异常情况，请输入管理员密码以进行下步操作!",
        "刪除考生",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputPlaceholder: "请输入管理员密码",
          inputType: "password",
          inputValidator: (value) => {
            if (!value) {
              return "请输入密码";
            } else {
              return true;
            }
          },
        }
      )
        .then(({ value }) => {
          checkPassword({
            password: value,
            schoolId: this.$store.state.user.deptId,
          }).then((res) => {
            examTeacherDel(id ? id : this.ids).then((res) => {
              this.$modal.msgSuccess("操作成功");
              this.$refs.tableList.clearSelection();
              this.ids = [];
              this.getList();
            });
          });
        })
        .catch(() => {});
    },

    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "/system/exam/teacher/import",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.deptId = "";
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.allDeptList = null;
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      if (!this.upload.deptId) {
        this.$modal.alertError("请选择导入学校");
        return;
      }
      this.$refs.upload.submit();
    },

    addTypeChange(value) {
      this.editForm = {
        addType: value,
        schoolId: "",
        teacherId: "",
        teacherName: "",
        phone: "",
        password: "",
        role: [],
        reviewSubject: [],
      };
      this.xklb = [];

      this.$nextTick(() => {
        this.$refs.editForm.clearValidate();
      });
    },
    schoolChange() {
      this.editForm.classId = "";
      this.editForm.studentId = "";

      teacherlist({
        pageNum: 1,
        pageSize: 9999,
        deptId: this.editForm.schoolId,
      }).then((res) => {
        this.jslb = res.rows;
      });

      let examSchoolId = this.xxlb.filter((item) => {
        return item.schoolId == this.editForm.schoolId;
      })[0].id;
      schoolsubjectlist({
        examId: this.xmxx.id,
        examSchoolId: examSchoolId,
      }).then((res) => {
        this.xklb = res.rows;
      });
    },

    teacherChange() {
      let teacher = this.jslb.filter((item) => {
        return item.userId == this.editForm.teacherId;
      })[0];

      this.editForm.password = teacher.password;
      this.editForm.phone = teacher.userName;
      this.editForm.role = teacher.userRoleVoList.map((item) => {
        return item.roleName;
      });
      this.editForm.reviewSubject = teacher.reviewSubject;
    },
    getExamSchoolId(value) {
      this.upload.examSchoolId = this.xxlb.filter((item) => {
        return item.schoolId == value;
      })[0].id;
    },

    roleFilter(role) {
      let roleArr = role.split(",");
      return this.roleList
        .filter((item) => {
          return roleArr.indexOf(item.roleId.toString()) != -1;
        })
        .map((item) => {
          return item.roleName;
        })
        .join(",");
    },

    qxopen() {
      this.loading = true;
      templatemenulist({ examId: this.xmxx.id })
        .then((res) => {
          this.qxglVisible = true;
          let qxData = JSON.parse(JSON.stringify(this.qxData));

          qxData.map((item) => {
            res.rows.map((v) => {
              if (item.roleId == v.roleId) {
                item.checked.push(v.menuId);
              }
            });
          });

          this.qxData = qxData;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    qxglbc() {
      this.loading = true;

      let arr = this.qxData.filter((item) => {
        return item.checked && item.checked.length > 0;
      });

      let data = [];
      arr.map((item) => {
        item.checked.map((v) => {
          data.push({
            roleId: item.roleId,
            menuId: v,
            examId: this.xmxx.id,
          });
        });
      });

      templatemenu(data)
        .then((res) => {
          this.qxglVisible = false;
          this.$modal.msgSuccess("操作成功");
        })
        .finally(() => {
          this.loading = true;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.editKmVisible {
  .el-input,
  .el-cascader,
  .el-select {
    width: 240px;
  }
}
</style>